﻿using CompanyManageSystem.Model;
using CompanyManageSystem.Service;
using DevExpress.Utils;
using DevExpress.Utils.Drawing;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Container;
using DevExpress.XtraEditors.Drawing;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraPrinting;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraTreeList;
using gregn6Lib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CompanyManageSystem.DLL
{
    public class BaseXtraForm :XtraForm
    {
        protected bool m_checkStatus;

        /// <summary>
        /// 窗口状态
        /// </summary>
        public EStatus FStatus { get; set; }

        /// <summary>
        /// 窗口状态
        /// </summary>
        public enum EStatus
        {
            Add = 0,
            Modify = 1,
            Look = 2,
        }

        public BaseXtraForm()
        {
            
        }
 
        #region 绑定复选框
        /// <summary>
        /// 绑定复选框
        /// </summary>
        /// <param name="view">视图</param>
        /// <param name="initCheck">初始化CheckBox</param>
        /// <param name="DisableEdit">不允许编辑</param>
        protected void BindCheckEdit(GridView view, bool initCheck = false, bool DisableEdit = true)
        {
            this.m_checkStatus = initCheck;
            GridColumn column = view.Columns.Add();
            column.FieldName = "IsChecked";
            column.Width = 0x4b;
            column.Fixed = FixedStyle.Left;
            column.OptionsColumn.ShowCaption = false;
            column.ColumnEdit = new RepositoryItemCheckEdit();
            column.Visible = true;

            if (view is BandedGridView)
            {
                (view as BandedGridView).Bands[0].Columns.Insert(0, column as BandedGridColumn);
            }
            else
            {
                view.Columns.Insert(0, column);
            }
            //是否多选
            //view.OptionsSelection.MultiSelect = true;
            view.OptionsSelection.MultiSelectMode = GridMultiSelectMode.RowSelect;
            if (DisableEdit)
            {
                view.OptionsBehavior.Editable = false;
            }

            view.Click += new EventHandler(this.view_Click);
            view.CustomDrawColumnHeader += new ColumnHeaderCustomDrawEventHandler(this.view_CustomDrawColumnHeader);
            view.DataSourceChanged += new EventHandler(this.view_DataSourceChanged);
            view.RowCellClick += new RowCellClickEventHandler(this.view_RowCellClick);
        }

        private void view_Click(object sender, EventArgs e)
        {
            GridView view = sender as GridView;
            if (view != null)
            {
                view.PostEditor();
                Point pt = view.GridControl.PointToClient(Control.MousePosition);
                GridHitInfo info = view.CalcHitInfo(pt);
                if ((info.InColumn && (info.Column != null)) && (info.Column.FieldName == "IsChecked"))
                {
                    info.Column.OptionsColumn.AllowSort = DefaultBoolean.False;
                    for (int i = 0; i < view.RowCount; i++)
                    {
                        view.SetRowCellValue(i, "IsChecked", !this.m_checkStatus);
                    }
                    this.m_checkStatus = !this.m_checkStatus;
                }
            }
        }

        private void view_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
        {
            string str = sender.GetType().ToString();
            if ((e.Column != null) && (e.Column.FieldName == "IsChecked"))
            {
                e.Info.InnerElements.Clear();
                e.Painter.DrawObject(e.Info);
                RepositoryItemCheckEdit columnEdit = e.Column.ColumnEdit as RepositoryItemCheckEdit;
                if (columnEdit != null)
                {
                    Graphics g = e.Graphics;
                    Rectangle bounds = e.Bounds;
                    CheckEditViewInfo viewInfo = columnEdit.CreateViewInfo() as CheckEditViewInfo;
                    CheckEditPainter painter = columnEdit.CreatePainter() as CheckEditPainter;
                    viewInfo.EditValue = this.m_checkStatus;
                    viewInfo.Bounds = bounds;
                    viewInfo.CalcViewInfo(g);
                    ControlGraphicsInfoArgs info = new ControlGraphicsInfoArgs(viewInfo, new GraphicsCache(g), bounds);
                    painter.Draw(info);
                    info.Cache.Dispose();
                }
                e.Handled = true;
            }
        }

        private void view_DataSourceChanged(object sender, EventArgs e)
        {
            GridView view = sender as GridView;
            GridColumn column = view.Columns.ColumnByFieldName("IsChecked");
            if (column != null)
            {
                column.Width = 50;
                column.OptionsColumn.ShowCaption = false;
                column.ColumnEdit = new RepositoryItemCheckEdit();
            }
        }

        private void view_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            GridView view = sender as GridView;
            if (((e.Column != null) && (e.Column.FieldName == "IsChecked")) && !view.OptionsBehavior.Editable)
            {
                GridHitInfo info = view.CalcHitInfo(new Point(e.X, e.Y));
                if (info.InRowCell)
                {
                    bool flag3 = Convert.ToBoolean(view.GetRowCellValue(info.RowHandle, "IsChecked"));
                    view.SetRowCellValue(info.RowHandle, "IsChecked", !flag3);
                }
            }
        }
        #endregion

        #region 获取勾选的行
        /// <summary>
        /// 获取勾选的行
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="view"></param>
        /// <returns></returns>
        protected List<T> GetChecked<T>(GridView view) where T : class
        {
            view.CloseEditor();
            GridColumn column = view.Columns.ColumnByFieldName("IsChecked");
            List<T> list = new List<T>();
            for (int i = 0; i < view.RowCount; i++)
            {
                if (Convert.ToBoolean(view.GetRowCellValue(i, "IsChecked")))
                {
                    list.Add(view.GetRow(i) as T);
                }
            }
            return list;
        }
        #endregion

        #region 弹出框
        /// <summary>
        /// 提示框
        /// </summary>
        /// <param name="msg"></param>
        protected virtual void ShowInfo(string msg)
        {
            XtraMessageBox.Show(msg,"温馨提示",MessageBoxButtons.OK,MessageBoxIcon.Asterisk);
        }
        #endregion

        #region 修改TreeList
        /// <summary>
        /// 重绘节点按钮
        /// </summary>
        /// <param name="treelist"></param>
        protected void CustomDrawNodeButton(TreeList treelist)
        {
            treelist.CustomDrawNodeButton += new DevExpress.XtraTreeList.CustomDrawNodeButtonEventHandler(this.DeptTree_CustomDrawNodeButton);
        }
        private void DeptTree_CustomDrawNodeButton(object sender, DevExpress.XtraTreeList.CustomDrawNodeButtonEventArgs e)
        {
            Rectangle rect = Rectangle.Inflate(e.Bounds, 0, -2);

            // painting background
            Brush backBrush = new LinearGradientBrush(rect, Color.Blue, Color.LightSkyBlue,
              LinearGradientMode.ForwardDiagonal);

            //填充指定矩形内部
            e.Graphics.FillRectangle(backBrush, rect);

            //绘画3D边框
            ControlPaint.DrawBorder3D(e.Graphics, rect, Border3DStyle.RaisedOuter);

            //要显示的图画
            string displayCharacter = e.Expanded ? "-" : "+";

            //水平,垂直居中
            StringFormat outCharacterFormat = new StringFormat();
            outCharacterFormat.Alignment = StringAlignment.Center;
            outCharacterFormat.LineAlignment = StringAlignment.Center;

            //绘画图标
            e.Graphics.DrawString(displayCharacter, new Font("Verdana", 8, FontStyle.Bold),
              new SolidBrush(Color.White), rect, outCharacterFormat);

            // 禁止默认的图标显示
            e.Handled = true;
        }

        /// <summary>
        /// 重绘节点图标
        /// </summary>
        /// <param name="treelist"></param>
        protected void CustomDrawNodeImages(TreeList treelist)
        {
            treelist.CustomDrawNodeImages += new DevExpress.XtraTreeList.CustomDrawNodeImagesEventHandler(this.DeptTree_CustomDrawNodeImages);
        }
        private void DeptTree_CustomDrawNodeImages(object sender, DevExpress.XtraTreeList.CustomDrawNodeImagesEventArgs e)
        {
            if (e.Node.Nodes.Count > 0)
            {
                if (e.Node.Expanded)
                {
                    e.SelectImageIndex = 1;
                    return;
                }
                e.SelectImageIndex = 0;
            }
            else
            {
                e.SelectImageIndex = 2;
            }
        }
        #endregion

        #region 绑定打印数据
        public static void FillRecordToReport<T>(IGridppReport Report, IEnumerable<T> entities)
        {
            PropertyInfo[] properties = typeof(T).GetProperties();
            foreach (T local in entities)
            {
                Report.DetailGrid.Recordset.Append();
                foreach (IGRField field in Report.DetailGrid.Recordset.Fields)
                {
                    PropertyInfo property = local.GetType().GetProperty(field.RunningDBField);
                    if ((property != null) && (property.GetValue(local, null) != null))
                    {
                        field.Value = property.GetValue(local, null);
                    }
                }
                Report.DetailGrid.Recordset.Post();
            }
        }
        #endregion

        #region 绑定指示器
        protected void BindRowIndicator(GridView girdView)
        {
            girdView.IndicatorWidth = 30;
            girdView.CustomDrawRowIndicator += new DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventHandler(gridView_CustomDrawRowIndicator);
        }
        private void gridView_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        #endregion

        #region 导出Excel文件
        protected virtual void ExportToExcel(EditorContainer grid)
        {
            SaveFileDialog dialog = new SaveFileDialog
            {
                Title = "导出Excel",
                Filter = "Excel文件(*.xls)|*.xls"
            };
            if (dialog.ShowDialog(this) == DialogResult.OK)
            {
                XlsExportOptions options = new XlsExportOptions();
                if (grid is GridControl)
                {
                    (grid as GridControl).ExportToXls(dialog.FileName, options);
                }
                else if (grid is TreeList)
                {
                    (grid as TreeList).ExpandAll();
                    (grid as TreeList).ExportToXls(dialog.FileName, options);
                }
                XtraMessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }
        #endregion

    }
}
